package com.cd.university.config.swagger;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈栋
 * @create 2021/9/3 19:07
 */
@Configuration
public class SwagerConfig implements WebMvcConfigurer {

        @Bean
        public Docket createRestApi() {
            Docket docket = new Docket(DocumentationType.SWAGGER_2);
            ApiInfoBuilder builder = new ApiInfoBuilder();
//            builder.title("University Scientific Research Project System");
            builder.title("高校科研管理系统");
            ApiInfo info = builder.build();
            docket.apiInfo(info);

            ApiSelectorBuilder selectorBuilder = docket.select();
            selectorBuilder.paths(PathSelectors.any()); // 把所有包下面的所有方法加入到Swagger中
            // 所有包下面的所有方法只要加上了@ApiOperation注解才会被加入到Swagger页面中
            selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
            docket = selectorBuilder.build();

//        JWT单点登录,以下的操作就是让swagger在测试我们的接口的时候会在请求头自动带上token,并不是jwt生成了token
            // 请求头里面的参数是token，名字是token，加在头
            ApiKey apiKey = new ApiKey("Token", "Token", "header");
            List<ApiKey> apiKeyList = new ArrayList<>();
            apiKeyList.add(apiKey);
            docket.securitySchemes(apiKeyList);

            // 设定令牌的作用域
//        accessEverything代表全局
            AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
            AuthorizationScope[] scopes = {scope};
            SecurityReference reference = new SecurityReference("Token", scopes);
            List refList = new ArrayList();
            refList.add(reference);
            SecurityContext context = SecurityContext.builder().securityReferences(refList).build();
            List cxtList = new ArrayList();
            cxtList.add(context);
            docket.securityContexts(cxtList);

            return docket;
        }
}
